<template>
  <div class="chat-container">
    <div v-if="enableVideo" class="video-area">
      <div v-if="!isInCall" class="video-controls">
        <el-button type="primary" @click="startVideoCall">
          <el-icon><VideoCamera /></el-icon>
          发起视频通话
        </el-button>
      </div>
      <div v-else class="video-streams">
        <div class="remote-stream">
          <video ref="remoteVideo" autoplay playsinline></video>
        </div>
        <div class="local-stream">
          <video ref="localVideo" autoplay playsinline muted></video>
        </div>
        <div class="call-controls">
          <el-button type="danger" @click="endCall">结束通话</el-button>
          <el-button @click="toggleMute">
            <el-icon><Microphone /></el-icon>
          </el-button>
          <el-button @click="toggleVideo">
            <el-icon><VideoCamera /></el-icon>
          </el-button>
        </div>
      </div>
    </div>

    <div class="chat-messages" ref="messagesContainer">
      <div
        v-for="message in messages"
        :key="message.id"
        :class="['message', message.senderId === currentUserId ? 'sent' : 'received']"
      >
        <div class="message-content">
          <div class="message-header">
            <span class="sender-name">{{ message.senderName }}</span>
            <span class="message-time">{{ formatTime(message.timestamp) }}</span>
          </div>
          <div class="message-text">{{ message.content }}</div>
        </div>
      </div>
    </div>

    <div class="chat-input">
      <el-input
        v-model="newMessage"
        placeholder="输入消息..."
        @keyup.enter="sendMessage"
      >
        <template #append>
          <el-button @click="sendMessage">发送</el-button>
        </template>
      </el-input>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, nextTick, onUnmounted } from 'vue'
import { Client } from '@stomp/stompjs'
import { format } from 'date-fns'
import { ElMessage } from 'element-plus'
import { VideoCamera, Microphone } from '@element-plus/icons-vue'

const props = defineProps<{
  conversationId: string
  currentUserId: string
  recipientId: string
  enableVideo?: boolean // 新增
}>()

const messages = ref([])
const newMessage = ref('')
const messagesContainer = ref(null)
const stompClient = ref(null)

// WebRTC 相关状态
const localStream = ref(null)
const remoteStream = ref(null)
const peerConnection = ref(null)
const isInCall = ref(false)

const connectWebSocket = () => {
  const client = new Client({
    brokerURL: 'ws://localhost:8080/ws',
    onConnect: () => {
      client.subscribe(`/user/queue/messages`, (message) => {
        const receivedMessage = JSON.parse(message.body)
        messages.value.push(receivedMessage)
        scrollToBottom()
      })
    }
  })
  client.activate()
  stompClient.value = client
}

const sendMessage = () => {
  if (!newMessage.value.trim()) return

  const message = {
    conversationId: props.conversationId,
    senderId: props.currentUserId,
    receiverId: props.recipientId,
    content: newMessage.value,
    timestamp: new Date()
  }

  stompClient.value.publish({
    destination: '/app/chat.private',
    body: JSON.stringify(message)
  })

  newMessage.value = ''
}

const scrollToBottom = async () => {
  await nextTick()
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

const formatTime = (timestamp: string) => {
  return format(new Date(timestamp), 'HH:mm')
}

onMounted(() => {
  connectWebSocket()
  if (props.enableVideo) {
    initializeWebRTC()
  }
})

onUnmounted(() => {
  endCall()
})

// 初始化WebRTC
const initializeWebRTC = async () => {
  const configuration = {
    iceServers: [
      { urls: 'stun:stun.l.google.com:19302' }
    ]
  }
  
  peerConnection.value = new RTCPeerConnection(configuration)
  
  // 处理远程流
  peerConnection.value.ontrack = (event) => {
    remoteStream.value = event.streams[0]
    remoteVideo.value.srcObject = remoteStream.value
  }
  
  // 处理ICE候选
  peerConnection.value.onicecandidate = (event) => {
    if (event.candidate) {
      stompClient.value.publish({
        destination: '/app/chat.webrtc',
        body: JSON.stringify({
          type: 'candidate',
          candidate: event.candidate,
          recipientId: props.recipientId
        })
      })
    }
  }
}

// 发起视频通话
const startVideoCall = async () => {
  try {
    localStream.value = await navigator.mediaDevices.getUserMedia({
      video: true,
      audio: true
    })
    
    localVideo.value.srcObject = localStream.value
    
    localStream.value.getTracks().forEach(track => {
      peerConnection.value.addTrack(track, localStream.value)
    })
    
    const offer = await peerConnection.value.createOffer()
    await peerConnection.value.setLocalDescription(offer)
    
    stompClient.value.publish({
      destination: '/app/chat.webrtc',
      body: JSON.stringify({
        type: 'offer',
        offer: offer,
        recipientId: props.recipientId
      })
    })
    
    isInCall.value = true
  } catch (error) {
    ElMessage.error('启动视频通话失败')
    console.error(error)
  }
}

// 结束通话
const endCall = () => {
  if (localStream.value) {
    localStream.value.getTracks().forEach(track => track.stop())
  }
  if (peerConnection.value) {
    peerConnection.value.close()
  }
  isInCall.value = false
  initializeWebRTC()
}

// 处理WebRTC信令
const handleWebRTCSignaling = async (message) => {
  const data = JSON.parse(message.body)
  
  switch (data.type) {
    case 'offer':
      await peerConnection.value.setRemoteDescription(new RTCSessionDescription(data.offer))
      const answer = await peerConnection.value.createAnswer()
      await peerConnection.value.setLocalDescription(answer)
      
      stompClient.value.publish({
        destination: '/app/chat.webrtc',
        body: JSON.stringify({
          type: 'answer',
          answer: answer,
          recipientId: data.senderId
        })
      })
      break
      
    case 'answer':
      await peerConnection.value.setRemoteDescription(new RTCSessionDescription(data.answer))
      break
      
    case 'candidate':
      await peerConnection.value.addIceCandidate(new RTCIceCandidate(data.candidate))
      break
  }
}
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.message {
  margin-bottom: 10px;
  display: flex;
}

.message.sent {
  justify-content: flex-end;
}

.message-content {
  max-width: 70%;
  padding: 10px;
  border-radius: 4px;
  background-color: #f4f4f5;
}

.message.sent .message-content {
  background-color: #409eff;
  color: white;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
  font-size: 12px;
}

.chat-input {
  padding: 10px;
  border-top: 1px solid #dcdfe6;
}

.video-area {
  height: 300px;
  background: #000;
  position: relative;
  margin-bottom: 20px;
}

.video-streams {
  height: 100%;
  position: relative;
}

.remote-stream {
  height: 100%;
}

.remote-stream video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.local-stream {
  position: absolute;
  right: 20px;
  bottom: 20px;
  width: 160px;
  height: 90px;
  border: 2px solid white;
  border-radius: 4px;
  overflow: hidden;
}

.local-stream video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.call-controls {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 10px;
}

.video-controls {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
</style>
